<template>
  <div class="device-block">
    <div class="header-image">
      <h3> {{ totalData.area_name || '' }} 的设备信息</h3>
    </div>
    <header class="regionMenu">
      <AreaMenu @areaClicked="handleAreaClicked"></AreaMenu>
    </header>
    <div class="area-setting" v-if="totalData && probeMoldCodeCount">
      <!-- 区域信息 -->
      <div class="info-and-types-container">
        <div class="filter-controls">
          <el-select v-model="selectedDeviceType" placeholder="选择设备类型" @change="filterDevices" class="custom-select">
            <el-option value="" label="所有设备"></el-option>
            <el-option v-for="(count, code) in probeMoldCodeCount" :key="code"
              :label="'设备类型' + code + ' (' + count + ')'" :value="code"></el-option>
          </el-select>
        </div>
        <el-descriptions border class="dark-descriptions">
          <template #title>
            <span class="custom-title">区域信息</span>
          </template>
          <el-descriptions-item label-class-name="my-label" class-name="my-content" label="平均电压">
            {{ totalData.area_average_voltage }} V
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label" class-name="my-content" label="平均功率">
            {{ totalData.area_average_power }} kW
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label" class-name="my-content" label="区域用电量">
            {{ totalData.area_total_ele_quantity }} 度
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-label" class-name="my-content" label="在线设备数">
            {{ deviceInlineCount }} / {{ totalData.device_count }}
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions border class="dark-descriptions">
          <template #title>
            <span class="custom-title">设备类型</span>
          </template>
          <div class="device-type-grid">
            <div v-for="(count, type) in formattedProbeMoldCodeCount" :key="type" class="device-type-item">
              <el-descriptions-item label-class-name="my-label" class-name="my-content" :label="`设备类型${type}`">
                {{ count }} / {{ totalData.device_count }}
              </el-descriptions-item>
            </div>
          </div>
        </el-descriptions>
      </div>
    </div>
    <div v-else class="loading-message">加载中...</div>
    <div class="device-list">
      <LittleDevice v-for="device in paginatedDevices" :key="device.probe_guid" :deviceId="device.id"
        :deviceData="device" />
    </div>
    <div class="pagination">
      <div class="pagination-controls">
        <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
        <span class="current-page">{{ currentPage }} / {{ totalPages }}</span>
        <button @click="nextPage" :disabled="currentPage === totalPages">
          下一页
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, defineProps, computed, onMounted, watch } from "vue";
import LittleDevice from "./littleDevice.vue";
import AreaMenu from "@/components/areaMenu.vue";
import { areaDataService } from "@/services";
import { ElDescriptions, ElDescriptionsItem, ElSelect, ElOption } from "element-plus";
import { useAreaStore } from '@/store/area';

const props = defineProps(["areaId"]);
const areaStore = useAreaStore();

const devices = ref([]);
const currentPage = ref(1);
const itemsPerPage = 4;
const totalData = ref({ area_name: '', area_average_voltage: 0, area_average_power: 0, area_total_ele_quantity: 0, device_count: 0 }); // 设置默认值
const deviceInlineCount = ref(0);
const probeMoldCodeCount = ref({});
const selectedDeviceType = ref(""); // 存储当前选中的设备类型

const totalPages = computed(() =>
  Math.ceil(filteredDevices.value.length / itemsPerPage)
);

const paginatedDevices = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage;
  return filteredDevices.value.slice(start, start + itemsPerPage);
});

const filteredDevices = computed(() => {
  if (!selectedDeviceType.value) {
    return devices.value;
  }
  return devices.value.filter(device => device.probe_mold_code == selectedDeviceType.value);
});

const fetchDevices = async (areaId) => {
  try {
    const response = await areaDataService.getRegionDataService(areaId);

    devices.value = Object.values(response.data.device_data || {});
    deviceInlineCount.value = response.data.device_inline_count || 0;
    probeMoldCodeCount.value = response.data.probe_mold_code_count || {};
    totalData.value = response.data || { area_name: '', area_average_voltage: 0, area_average_power: 0, area_total_ele_quantity: 0, device_count: 0 }; // 设置默认值
    currentPage.value = 1;

    devices.value.sort((a, b) => {
      // 先根据在线状态排序，在线设备排在前面
      const stateCompare = a.state - b.state;
      if (stateCompare !== 0) {
        return stateCompare;
      }

      // 如果在线状态相同，则根据设备类型排序
      const typePriority = (type) => {
        if (type === 28) return 1;
        if (type === 29) return 2;
        return 3; // 其他类型排在最后
      };

      return typePriority(a.probe_mold_code) - typePriority(b.probe_mold_code);
    });
  } catch (error) {
    console.error("Error fetching devices:", error);
  }
};
console.log("totalData.value原",totalData.value)

const prevPage = () => {
  if (currentPage.value > 1) currentPage.value--;
};

const nextPage = () => {
  if (currentPage.value < totalPages.value) currentPage.value++;
};

const filterDevices = () => {
  currentPage.value = 1; // 重置当前页为第一页
};

const formattedProbeMoldCodeCount = computed(() => {
  return Object.keys(probeMoldCodeCount.value).reduce((acc, key) => {
    acc[` ${key}`] = probeMoldCodeCount.value[key];
    return acc;
  }, {});
});

const handleAreaClicked = (areaId) => {
  areaStore.setSelectedAreaId(areaId);
  fetchDevices(areaId); // 加载所选区域的数据
};

watch(() => props.areaId, fetchDevices);
onMounted(() => {
  if (props.areaId) {
    fetchDevices(props.areaId);
  } else {
    fetchDevices(''); // 替换为实际的默认区域ID
  }
});
</script>

<style scoped>
/* 描述列表 */
:deep(.my-label) {
  border: #2a2c42;
  background: #2a2c42 !important;
  color: #ffffff !important;
}

:deep(.my-content) {
  color: white !important;
  background: #2a2c42;
}

.device-block {
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  border: 1px solid #cccccc;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
  background-color: #2a2c42;
  width: 100%;
  height: 620px;
  /* Adjusted height */
}

.el-select {
  width: 200px;
  margin-top: 85px;
}

.custom-title {
  color: #ffffff;
  /* 替换为您希望的颜色 */
}

.header-image {
  background-image: url("../assets/header-bg.png");
  background-size: cover;
  background-position: center;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #ffffff;
  font-size: 20px;
}

.info-and-types-container {
  display: flex;
  border-radius: 5px;
  background-color: #001f3f;
  /* 深蓝色背景 */
}

.info-column {
  display: flex;
  flex-direction: column;
}

.device-type-header {
  text-align: center;
  font-size: 18px;
}

.current-page {
  color: #ffffff;
}

.device-type-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.device-type-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.device-list {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 10px;
  overflow-y: auto;
  grid-auto-flow: dense;
}

.pagination {
  position: absolute;
  bottom: 0;
  width: 100%;
  background: #2a2c42;
  border-top: 1px solid #cccccc;
  display: flex;
  justify-content: center;
}

.pagination-controls button {
  margin: 0 5px;
  padding: 5px 10px;
  border: 1px solid #cccccc;
  background-color: #ffffff;
  cursor: pointer;
}

.el-descriptions,
.el-descriptions-item {
  background-color: #001f3f !important;
  /* 深蓝色背景 */
  color: #a07474 !important;
  /* 设置文本颜色为白色 */
}

.el-descriptions-item__label {
  color: #ffffff !important;
  /* 设置标签颜色为白色 */
}

.regionMenu {
  width: 100%;
  background-color: #fff;
  /* 菜单背景色 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  /* 阴影效果 */
}
</style>
